package com.wxq.demo.controller;

import com.wxq.demo.model.User;
import com.wxq.demo.service.MailService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;

@RestController
public class MailController {
    @Autowired
    private MailService mailService;

    @Value("${spring.mail.username}")
    private String form;



    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/sendSimpleMail")
    public void sendSimpleMail() {
        mailService.sendSimpleMail(form, "***@qq.com", "Springboot邮件发送测试", "测试简单邮件发送");
    }

    @GetMapping("/sendAttachFileMail")
    public void sendAttachFileMail() {
        mailService.sendAttachFileMail(form, "***@qq.com", "Springboot邮件发送测试", "测试带附件邮件发送",
                new File("C:\\Users\\WEIXQ\\Pictures\\Saved Pictures\\0018.PNG"));
    }

    @GetMapping("/sendMailWithImg")
    public void sendMailWithImg() {
        mailService.sendMailWithImg(form, "***@qq.com", "Springboot邮件发送测试",
                "<html><body><div>测试带图片资源的邮件发送:" +
                        "图片1：<div><img src='cid:p01'/></div>" +
                        "图片2：<div><img src='cid:p02'/></div>" +
                        "</div></body></html>",
                new String[]{"C:\\Users\\WEIXQ\\Pictures\\Camera Roll\\风景\\北海道\\北海道.jpg", "C:\\Users\\WEIXQ\\Pictures\\Camera Roll\\风景\\北海道\\北海道-1422843535558.jpg"},
                new String[]{"p01", "p02"});
    }

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @GetMapping("/sendHtmlMailFreemarker")
    public void sendHtmlMailFreemarker() {
        try {
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("mailtemplate.ftl");
            User user = new User();
            user.setUsername("缥缈陌上");
            user.setGender("男");
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, user);
            mailService.sendHtmlMail(form, "***@qq.com", "Springboot邮件发送测试", text);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/sendHtmlMailThymeleaf")
    public void sendHtmlMailThymeleaf() {
        Context context = new Context();
        context.setVariable("username", "缥缈陌上");
        context.setVariable("gender", "男");
        String text = templateEngine.process("mailtemplate.html", context);
        mailService.sendHtmlMail(form, "***@qq.com", "Springboot邮件发送测试", text);
    }
}
